﻿using System.Collections.Generic;
using System.IO;
using System.Windows;
using Microsoft.Win32;
using TrafficCountingTool.Models;

namespace TrafficCountingTool.Core
{
    public static class SavingHelper
    {
        public static AppCache LoadFile()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "存档文件(*.pjson)|*.pjson";
            openFileDialog.ShowDialog();

            var path = openFileDialog.FileName;
            if (string.IsNullOrEmpty(path))
            {
                return null;
            }

            return ProjectFileHelper.Load(path).ToAppCache();
        }

        public static void SaveFile(AppCache appCache)
        {
            if (appCache.ProjectFilePath != null)
            {
               ProjectFileHelper.Save(appCache.ProjectFilePath, appCache.ToProjectFile());
                return;
            } 

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "存档文件(*.pjson)|*.pjson";
            saveFileDialog.ShowDialog();

            if (string.IsNullOrEmpty(saveFileDialog.FileName))
            {
                return;
            }

            appCache.ProjectFilePath = saveFileDialog.FileName;
            ProjectFileHelper.Save(appCache.ProjectFilePath, appCache.ToProjectFile());
        }

        public static void ExportFile(AppCache appCache)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            //saveFileDialog.Filter = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(*.xls)|*.xls|文本文件(*.txt)|*.txt";
            saveFileDialog.Filter = "Excel 工作簿(*.xlsx)|*.xlsx|文本文件(*.txt)|*.txt";
            saveFileDialog.ShowDialog();

            var fileName = saveFileDialog.FileName;

            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }

            var extension = Path.GetExtension(fileName);
            ExportingFileType exportingFileType = ExportingFileType.Xlsx;
            switch (extension)
            {
                case ".txt":
                    exportingFileType = ExportingFileType.Txt;
                    break;
                case ".xlsx":
                    exportingFileType = ExportingFileType.Xlsx;
                    break;
                //case ".xls":
                //    exportingFileType = ExportingFileType.Xls;
                //    break;
            }

            ExportingFileHelper.Export(appCache, exportingFileType, saveFileDialog.FileName);

            MessageBox.Show("导出成功！");
        }

        public static string ImportFile()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "avi文件(*.avi)|*.avi" + 
                "|mp4文件(*.mp4)|*.mp4" +
                "|wmv文件(*.wmv)|*.wmv" +
                "|所有文件(*.*)|*.*";
            openFileDialog.ShowDialog();

            return openFileDialog.FileName;
        }
    }
}